package cn.yywd_123.Light.main.utils;

/*
 *  Author: yywd_123
 *  Date: 2022/8/17
 */

import cn.yywd_123.Light.AgentMain;
import cn.yywd_123.Light.main.utils.codeMap.TransformField;
import cn.yywd_123.Light.main.utils.codeMap.TransformMethod;
import javassist.*;

public class CodeTransformer {
	public CodeParser codeParser = new CodeParser(AgentMain.getArg());

	public void transformMethod(CtMethod target) throws CannotCompileException {
		TransformMethod transformMethod;
		if ((transformMethod = codeParser.getTransformMethod(target.getLongName())) != null) {
			if (transformMethod.getAction().equalsIgnoreCase("setPermission")) {
				if (transformMethod.getTransformSource().equalsIgnoreCase("public")) {
					target.setModifiers(Modifier.PUBLIC);
				}
				else if (transformMethod.getTransformSource().equalsIgnoreCase("private")) {
					target.setModifiers(Modifier.PRIVATE);
				}
				else throw new IllegalArgumentException("[Light] 无效的访问权限: [" + transformMethod.getTransformSource() + "]");
			} else if (transformMethod.getAction().equalsIgnoreCase("setBody")) {
				target.setBody(transformMethod.getTransformSource());
			}
			else if (transformMethod.getAction().equalsIgnoreCase("insertBefore")) {
				target.insertBefore(transformMethod.getTransformSource());
			}
			else if (transformMethod.getAction().equalsIgnoreCase("insertAfter")) {
				target.insertAfter(transformMethod.getTransformSource());
			}
			else throw new IllegalArgumentException("[Light] 无效的转换操作: [" + transformMethod.getTransformSource() + "]");
		}
	}

	public void transformField(String className, CtField target) throws CannotCompileException {
		TransformField transformField;
		if ((transformField = codeParser.getTransformField(className + "." + target.getName())) != null) {
			if (transformField.getPermission().equalsIgnoreCase("public")) target.setModifiers(Modifier.PUBLIC);
			else if (transformField.getPermission().equalsIgnoreCase("private")) target.setModifiers(Modifier.PRIVATE);
			else throw new IllegalArgumentException("[Light] 无效的权限: [" + transformField.getPermission() + "]");
		}
	}
}
